import os
# import jsonpath
from urllib.parse import unquote

import jsonpath
from django.db.models import Q
from xmindparser import xmind_to_dict
import json
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator
from django.shortcuts import render
from .models import FlowCases
from userManage.models import User
from projectManage.models import Project
from django.core.paginator import PageNotAnInteger, EmptyPage
from django.shortcuts import redirect
from django.shortcuts import reverse
import time
from django.http import HttpResponse, Http404
from app01.views import export


# Create your views here.
def transfer_the_page_range(p, paginator):
    """
    页数进行转换
    :param p:
    :param paginator:
    :return:
    """
    if paginator.num_pages > 5:
        if p - 5 < 1:
            if paginator.num_pages > 10:
                page_range = range(1, 11)
            else:
                page_range = range(1, paginator.num_pages + 1)
        elif p + 5 > paginator.num_pages:
            page_range = range(p - 5, paginator.num_pages + 1)
        else:
            page_range = range(p - 5, p + 5)
    else:
        page_range = paginator.page_range
    return page_range


def flow_case(request):
    cases = FlowCases.objects.all().order_by("-id")
    p = request.GET.get('current_page', 1)
    paginator = Paginator(cases, 10)
    p = int(p)
    projects = Project.objects.all()
    users = User.objects.all()
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'flowCase/flow_case_index.html', locals())


def flow_case_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        case = FlowCases.objects.all()
        project_name = request.POST.get('project_name')
        try:
            case.create(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='流程',
                project_id=project_name, system=project_name, real_result=''
            )
            return redirect(reverse('flowCase:flow_case'))
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")
    else:
        return HttpResponse("demo")


def flow_case_delete(request, case_id):
    FlowCases.objects.get(pk=case_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)


def flow_edit_case(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = FlowCases.objects.filter(id=case_id)
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.create(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='新增',
                project_id=project_id, real_result=real_result
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")


def flow_case_search(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = FlowCases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                         Q(create_time__lte=end_date + " 23:59:59"),
                                                         title__contains=case_title, page='流程',
                                                         creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = FlowCases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                         title__contains=case_title, page='流程',
                                                         creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = FlowCases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                         title__contains=case_title, page='流程',
                                                         creator__contains=case_creator).order_by('-id')
            else:
                search_result = FlowCases.objects.filter(title__contains=case_title, page='流程',
                                                         creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'flowCase/flow_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def deal_with_xmind(file_path):
    xm = xmind_to_dict(file_path)[0]['topic']
    # indent为显示json格式，ensure_ascii未显示为中文，不显示ASCII码
    # dict_result = json.dumps(xm, indent=2, ensure_ascii=False)
    return xm


def upload(request):
    if request.method == 'POST':
        file = request.FILES.get("import_file", None)
        if file is None:
            return HttpResponse("文件为空")
        else:
            if file.name.split('.')[-1] == "xmind":
                file_name = os.path.join(settings.MEDIA_ROOT, file.name)
                with open(file_name, 'wb+') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
                ReadXmind = xmind_to_dict(file_name)
                os.remove(file_name)
                case_model_object = FlowCases.objects.all()
                # 系统名
                system = jsonpath.jsonpath(ReadXmind[0], '$.topic.title')[0]
                case_content = jsonpath.jsonpath(ReadXmind[0], '$.topic.topics')[0]
                cases = jsonpath.jsonpath(case_content[0], '$.topics')[0]
                # 创建者
                creator = jsonpath.jsonpath(case_content[0], '$.title')[0]
                for module in cases:
                    # 一级模块
                    # TODO 预留字段
                    # TODO 这一层级的格式判断

                    judge_flag_0 = 7  # 判断标识
                    title_num = json.dumps(module, ensure_ascii=False).count('title')  # 统计title数量进行判断
                    if title_num >= judge_flag_0:
                        senior_module = jsonpath.jsonpath(module, '$.title')[0]
                        # 子模块
                        sub_module_list = jsonpath.jsonpath(module, '$.topics')[0]
                        for sub_module in sub_module_list:
                            # TODO 预留字段
                            # TODO 这一层级的格式判断
                            # sub_module 子模块这一层级创建用例，共用主模块名
                            # sub_module_name子模块名称
                            sub_module_name = jsonpath.jsonpath(sub_module, '$.title')[0]
                            case_list = jsonpath.jsonpath(sub_module, '$.topics')[0]
                            for case in case_list:
                                print(case)
                                case_title_list = []
                                case_steps_list = []
                                case_expect_result_list = []
                                case_precondition_list = []
                                case_level_list = []
                                case_to_string = json.dumps(case, ensure_ascii=False)
                                # case_to_string.count('title'))) 通过查找title数量，判断文件格式是否符合模板要求
                                judge_flag = case_to_string.count('title')
                                if judge_flag == 5:
                                    # 用例标题
                                    case_title = jsonpath.jsonpath(case, '$.title')[0]
                                    list1 = jsonpath.jsonpath(case, '$.topics')[0]
                                    # 预置条件
                                    pre_condition = jsonpath.jsonpath(list1[0], '$.title')[0]
                                    list2 = jsonpath.jsonpath(list1[0], '$.topics')[0]
                                    # 测试步骤
                                    case_steps = jsonpath.jsonpath(list2[0], '$.title')[0]
                                    list3 = jsonpath.jsonpath(list2[0], '$.topics')[0]
                                    # 预期结果
                                    case_expect_result = jsonpath.jsonpath(list3[0], '$.title')[0]
                                    list4 = jsonpath.jsonpath(list3[0], '$.topics')[0]
                                    # 用例等级
                                    case_level = jsonpath.jsonpath(list4[0], '$.title')[0]
                                    case_title_list += [case_title]
                                    case_steps_list += [case_steps]
                                    case_level_list += [case_level]
                                    case_expect_result_list += [case_expect_result]
                                    case_precondition_list += [pre_condition]
                                    # create、system共用
                                    for _ in range(len(case_title_list)):
                                        case_model_object.create(
                                            title=case_title_list[_], pre_condition=case_precondition_list[_],
                                            creator=creator,
                                            case_steps=case_steps_list[_], case_level=case_level_list[_],
                                            expect_result=case_expect_result_list[_],
                                            project_id=system, create_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                                            remarks='',
                                            page='流程', system=system, real_result=''
                                        )

                                else:
                                    return HttpResponse(f"{case}用例不符合模板规则，请检查后重新上传！")

                    else:
                        return HttpResponse("用例不符合模板规则，请检查后重新上传！")
                return redirect(reverse('flowCase:flow_case'))
            else:
                return HttpResponse("文件格式错误！")


def upload_bak(request):
    """
    上传文件
    """
    if request.method == 'POST':
        file = request.FILES.get("import_file", None)
        if file is None:
            return HttpResponse("文件为空")
        else:
            if file.name.split('.')[-1] == "xmind":
                file_name = os.path.join(settings.MEDIA_ROOT, file.name)
                with open(file_name, 'wb+') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
                result = deal_with_xmind(file_name)
                os.remove(file_name)
                print("*****************", result)
                case_title = []
                case_steps = []
                case_expect_result = []
                level = []
                system = result['title']
                case_precondition = f"已登录{system}"
                module1 = result['topics'][0]['title']
                module2 = result['topics'][0]['topics'][0]['title']
                module3 = result['topics'][0]['topics'][0]['topics'][0]['title']
                case_title += [result['topics'][0]['topics'][0]['topics'][0]['topics'][0]['title']]
                case_steps += [result['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['title']]
                case_expect_result += [
                    result['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['title']]
                level += [
                    result['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0][
                        'title']]
                print(level)
                creator = \
                result['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0]['topics'][0][
                    'topics'][0]['title']
                case = FlowCases.objects.all()
                for _ in range(len(case_title)):
                    case.create(
                        title=case_title[_], pre_condition=case_precondition, creator=creator,
                        case_steps=case_steps[_], case_level=level[_], expect_result=case_expect_result[_],
                        project_id=system, create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='',
                        page='流程', system=system, real_result=''
                    )
                print(system, module1, module2, module3)
                return redirect(reverse('flowCase:flow_case'))
            else:
                return HttpResponse("文件格式错误！")


def flow_case_edit(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = FlowCases.objects.filter(id=case_id)
        try:

            case.update(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='流程',
                project_id=project_name, real_result=real_result, system=project_name
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")

def media_file_download(request, file_path):
    file_path = os.path.abspath(f'{file_path}')
    with open(file_path, 'rb') as f:
        try:
            response = HttpResponse(f)
            response['content_type'] = "application/octet-stream"
            response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
            return response
        except Exception:
            raise Http404


def flow_case_search_result_export(request):
    referer = request.headers.get('Referer')
    params_list = referer.split('&')
    params_dict = {}
    params_list = params_list[1:]
    for param in params_list:
        (key, value) = param.split('=')
        params_dict[key] = value
    start_date = params_dict['start_date']
    end_date = params_dict['end_date']
    case_title = params_dict['case_title']
    case_title = unquote(case_title, 'utf-8').strip("+")
    case_title = case_title.strip()
    case_creator = params_dict['case_creator']
    case_creator = unquote(case_creator, 'utf-8').strip("+")
    case_creator = case_creator.strip()
    if start_date and end_date:
        search_result = FlowCases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                 Q(create_time__lte=end_date + " 23:59:59"),
                                                 title__contains=case_title,
                                                 creator__contains=case_creator,
                                                 page__exact='流程').order_by('-id')
    elif start_date:
        search_result = FlowCases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                 title__contains=case_title,
                                                 creator__contains=case_creator,
                                                 page__exact='流程').order_by('-id')
    elif end_date:
        search_result = FlowCases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                 title__contains=case_title,
                                                 creator__contains=case_creator,
                                                 page__exact='流程').order_by('-id')
    else:
        search_result = FlowCases.objects.filter(title__contains=case_title,
                                                 creator__contains=case_creator,
                                                 page__exact='流程').order_by('-id')
    print(type(search_result))
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=newPageCase_{excel_postfix}.xls'
    return export(excel_name, search_result)


def flow_case_export(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = FlowCases.objects.all().filter(page__exact='流程')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=flowCase_{excel_postfix}.xls'
    return export(excel_name, cases)
